<?php


class stringTool
{
    static function encode($string, $secret, $return = false)
    {
        $a = base64_encode($string);
        $b = str_split($a);
        $c = "";
        foreach ($b as $value) {
            $x_a = ord($value);
            $x_b = 127 - $x_a;
            $x_c = dechex($x_b);
            if (strlen($x_c) == 1) {
                $x_c = "0" . $x_c;
            }
            $c .= $x_c;
        }
        $d = substr(hash("sha256", $secret), 0, strlen($secret));
        $c_a = str_split($c);
        $d_a = str_split($d);
        $f = "";
        $index = 0;
        foreach ($c_a as $value) {
            $v_a = $value;
            $v_b = $d_a[$index++ % count($d_a)];
            $v_c = decbin(ord($v_a) + ord($v_b));
            if (strlen($v_c) == 7){
                $v_c = "0" . $v_c;
            }
            $v_d = str_replace("1","I",$v_c);
            $v_d = str_replace("0","l",$v_d);
            $f .= $v_d;
        }
        $result = $f;
        if ($return) {
            return $result;
        } else {
            echo $result;
        }
    }

    static function decode($string, $secret, $return = false)
    {
        if (preg_match('/[^Il]/',$string)){
            $result = "数据错误";
        }else {
            $a = str_split(str_replace("I", "1", str_replace("l", "0", $string)), 8);
            $b = str_split(substr(hash("sha256", $secret), 0, strlen($secret)));
            $index = 0;
            $c = "";
            foreach ($a as $value) {
                $x_a = bindec($value);
                $x_b = ord($b[$index++ % count($b)]);
                $x_c = chr($x_a - $x_b);
                $c .= $x_c;
            }
            $d = str_split($c, 2);
            $e = "";
            foreach ($d as $value) {
                try {
                    if (127 - hexdec($value)<0){
                        return "数据错误";
                    }
                    $v_a = chr(127 - hexdec($value));
                    $e .= $v_a;
                } catch (Exception $e) {
                    die("密码错误");
                }
            }
            $result = base64_decode($e);
        }
        if ($return){
            return $result;
        }else{
            echo $result;
        }
    }
}